<?php
/**
 * (logic)
 */
namespace App\Logic\MonthlyReport;

use App\Models\MonthlyReport\Cost\LogisticsBalanceInit;
use App\Models\MonthlyReport\Cost\LogisticsOSBalanceInit;
use App\Models\MonthlyReport\Cost\LogisticsBalance;
use App\Models\MonthlyReport\Cost\LogisticsOSBalance;
use Illuminate\Support\Facades\DB;
class InitLogistics
{
    public static function exe($func)
    {
        try{
            DB::beginTransaction();
            self::{$func}();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    private static function _exeInitOS(){
        $lines = LogisticsOSBalanceInit::query()
            ->select('area_id','psku_id')
            ->distinct()
            ->get();
        foreach ($lines as $index => $line){
            $model = LogisticsOSBalanceInit::query()
                ->where('area_id',$line->area_id)
                ->where('psku_id',$line->psku_id)
                ->orderBy('delivered_at','DESC')
                ->first();
            $num = $index + 1;
            $str = str_pad($num, 5, "0", STR_PAD_LEFT);
            LogisticsOSBalance::query()->create(
                [
                    'area_id' => $line->area_id,
                    'psku_id' => $line->psku_id,
                    'delivery_no' => 'IND201202'.$str,
                    'delivered_at' => "2020-12-02 00:00:00",
                    'b_num' => $model->b_num,
                    'b_price' => $model->b_price,
                    'b_balance_sale' => $model->b_num
                ]
            );
        }
    }

    private static function _exeInitFBA(){
        $lines = LogisticsBalanceInit::query()
            ->select('area_id','psku_id')
            ->distinct()
            ->get();
        foreach ($lines as $index => $line){
            $model = LogisticsBalanceInit::query()
                ->where('area_id',$line->area_id)
                ->where('psku_id',$line->psku_id)
                ->where('b_num','>',0)
                ->orderBy('delivered_at','DESC')
                ->first();
            $num = $index + 1;
            $str = str_pad($num, 5, "0", STR_PAD_LEFT);
            LogisticsBalance::query()->create(
                [
                    'area_id' => $line->area_id,
                    'psku_id' => $line->psku_id,
                    'delivery_no' => 'IND201201'.$str,
                    'delivered_at' => "2020-12-01 00:00:00",
                    'b_num' => $model->b_num,
                    'b_price' => $model->b_price,
                    'b_balance_sale' => $model->b_num
                ]
            );
        }
    }
}
